// vi:si:et:sw=4:sts=4:ts=4
package cat.hex.trainoid;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class trainoid extends Activity
{
    /**
     * Singleton instance
     */
    private static trainoid instance;

    /**
     * DB Adapter
     */
    protected DbAdapter mDbHelper;

    static final private String tag = "trainoid"; // for Log

    /* Menu constants */
    private static final int EDIT_ID = Menu.FIRST;
    private static final int STATISTICS_ID = Menu.FIRST + 1;
    private static final int TRACK_LIST_ID = Menu.FIRST + 2;
    private static final int MAP_ID = Menu.FIRST + 3;

    private static final int GPS_ID = Menu.FIRST + 4;
    private static final int ACTIVITY_GPS = 4;

    protected static final int ACTIVITY_EDIT = 0;
    protected static final int ACTIVITY_STATISTICS = 1;
    protected static final int ACTIVITY_TRACK_LIST = 2;
    protected static final int ACTIVITY_MAP = 3;

    protected Track mTrack;
    protected User mUser;
    protected Map mMap;
    protected GPSReceiver service;

    //private static boolean isRecording;

    /*
     * User identifier.
     * Right now, this program just will support one User at time.
     */
    public final static long DEFAULT_USER_ID = 1;
    protected long mUserId = DEFAULT_USER_ID; // This variable is not necessary! must be mTrack.getID();

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        /**
         * Initalizing singleton instance
         */
        if (instance == null)
            instance = this;

        // DB Adapter initialization
        mDbHelper = new DbAdapter(this);

        // Debug
        Log.d(tag, "onCreate - Before start GPS service");
        /* Start GPS Service */
        startService(new Intent(this, GPSReceiver.class));
        service = GPSReceiver.getInstance();
        Log.d(tag, "GPS service started");


        /* status initialization */
        mMap = null;

        /* Initialize mUser variable */
        mUser = new User(mUserId, (Context)this);

        /* Creating new track */
        //createNewTrack();

        /* Initializing Layout data */
        setContentView(R.layout.main);

        final Button buttonMapView = (Button) findViewById(R.id.v_b_map_view);
        buttonMapView.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
        {
            showMap();
        }
        });

        final Button buttonNewTrack = (Button) findViewById(R.id.v_b_new_track);
        buttonNewTrack.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
        {
            createNewTrack();
            showMap();
        }
        });

        final Button buttonTrackList = (Button) findViewById(R.id.v_b_track_list);
        buttonTrackList.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
        {
            showTrackList();
        }
        });

        /* Fill summary screen */
        fillText();        
    }

    /**
     * Options menu function creation
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);

        menu.add(0, EDIT_ID, 0, R.string.menu_edit);
        menu.add(0, STATISTICS_ID, 0, R.string.menu_statistics);
        menu.add(0, TRACK_LIST_ID, 0, R.string.menu_track_list);
        menu.add(0, MAP_ID, 0, R.string.menu_map);

        menu.add(0, GPS_ID, 0, R.string.menu_gpslist);

        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {
        switch(item.getItemId())
        {
            case GPS_ID:
                showGPS();
                return true;
            case MAP_ID:
                showMap();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * This function starts the GPS position list activity
     */
    private void showGPS()
    {
        Intent i = new Intent(this, TrackList.class);
        startActivityForResult(i, ACTIVITY_GPS);
    }

    /**
     * This function starts the map activity
     */
    private void showMap()
    {
        Intent i = new Intent(this, Map.class);
        i.putExtra("mTrackId", -1);
        startActivityForResult(i, ACTIVITY_MAP);
    }

    /**
     * Function to get the singleton instance
     * 
     * @return trainoid singleton
     */
    public static trainoid getInstance()
    {
        if (instance == null)
        {
            //Toast.makeText(this, "(by hand) ERROR: unable to save the gps position mTrack == null", Toast.LENGTH_SHORT).show();
            instance = new trainoid();
        }

        return instance;
    }

    /**
     * Sets the text on summary activity
     */
    protected void fillText()
    {
        ((TextView) findViewById(R.id.v_stats_distance_value)).setText(mUser.getTotalDistance() + " m");
        ((TextView) findViewById(R.id.v_stats_time_value)).setText(mUser.getTotalTime()+ " min");

        ((TextView) findViewById(R.id.v_user_name)).setText(mUser.getName());
        ((TextView) findViewById(R.id.v_user_weight)).setText(mUser.getWeight()+ " kg");
        ((TextView) findViewById(R.id.v_user_height)).setText(mUser.getHeight()+ " cm");
    }

    /**
     * This function initializes a new empty track
     */
    protected void createNewTrack()
    {
        if (service.isRecording() == true)
        {
            Toast.makeText(this, "Another track is recording, you must stop it first", Toast.LENGTH_LONG).show();
        }
        else
        {
            /*
               if (mTrack != null)
               mTrack.destroy();

               mTrack = new Track(this);
               */
            service.setTrackId(-1);
        }

    }

    /**
     * This function defines a new track identified by the parameter
     * @param trackid the identifier of the new track
     */
    public void setTrack(long trackid)
    {
        /*
           if (mTrack != null)
           free(mTrack);
           */
        mTrack = new Track(trackid, this);

        Log.d(tag, "new trackid: " + mTrack.getTrackId());
    }

    /**
     * This function starts the tracks list activity
     */
    protected void showTrackList()
    {
        Intent i = new Intent(this, TrackList.class);
        startActivityForResult(i, ACTIVITY_TRACK_LIST);
    }

    /**
     * This function sets the recording value to false for non continue recording track
     */
    protected void stopRecording()
    {
        //isRecording = false;
        service.stopRecording();

        ArrayList<Location> a = service.getPath();

        if (a == null)
        {
            Toast.makeText(this, "path is null, wth", Toast.LENGTH_LONG).show();
            return;
        }

        mTrack.setPath(a);
        mTrack.saveTrack();
    }

    /**
     * This function sets the recording value to true for start recordng track
     */
    protected void startRecording()
    {
        //isRecording = true;
        service.startRecording();
    }

    /**
     * Sets the parameter map as trainoid default map view
     * @param map
     */
    public void setMap(Map map)
    {
        Log.w(tag, "this function must not be used (trainoid.setMap)");
        mMap = map;
    }

    /**
     * This function returns the recording status
     * @return boolean that means recording status
     */
    public boolean isRecording()
    {
        return service.isRecording();
    }

    /**
     * This function returns if the map
     * @return
     */
    public boolean isMapCreated()
    {
        return (mMap == null);
    }

    public void invalidateMap()
    {
        if (mMap != null)
            mMap.refresh();
    }
}
